package com.yc.demo.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *	案例：根据输入的多个爱好值， 生成一个下拉列表
 *
 *	数组型的请求参数： ?a=1&b=2&c=3&a=4
 *
 * 	<select>
 * 		<option>a</option>
 * 		<option selected>b</option>
 * 		<option>c</option>
 * 	</select>
 *	http://127.0.0.1/C94-S2-Ply-servlet/likes.s?
 *			like=篮球&like=电影&like=看书&like=手游&selected=看书
 */
@WebServlet("/likes.s")
public class LikesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		// 获取爱好数组  数组型参数
		String[] likes = request.getParameterValues("like");
		String selected = request.getParameter("selected");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print("<select>");
		for(String like : likes) {
			if(like.equals(selected)) {
				out.append("<option selected>");
			} else {
				out.append("<option>");
			}
			out.append(like).append("</option>");
		}
		out.print("</select>");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
